//
//  DBHistoryDataSr03.m
//  CareRingApp
//
//  Created by Linktop on 2022/8/15.
//

#import "DebugDBHistoryDataALL.h"
#import "HMDBManager.h"
#import "ConfigModel.h"
#import "TimeUtils.h"
#import "DBHeartRate.h"
#import "SRHistoryDataSR03+OtherCalc.h"
#import "DBSleepData.h"
#import "ReadyDrawObj.h"


NSString * const TABLE_NM_HISDATA_ALL_DEBUG = @"table_his_all_debug";


@implementation DebugDBHistoryDataALL

#pragma mark --数据库相关
//创建数据库
+(void)createTable
{
//#if SAVE_ALL_HIS_FOR_DEBUG == 1
    
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        //创建数据库表
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(time DOUBLE, macAdres TEXT NOT NULL, dataUuid INT, isWear BOOLEAN, soprtTimes INT, steps INT, skinTemp FLOAT, bloodOxygen FLOAT, hrv FLOAT, deviceModifyHeartRate INT, heart_ori_1 INT, heart_ori_2 INT, heart_ori_3 INT, measureType INT, br INT, isSportMode BOOLEAN, lis2ds12 BOOLEAN, isCharging BOOL, fmtTime TEXT, battery INT, PRIMARY KEY(time, macAdres))", TABLE_NM_HISDATA_ALL_DEBUG];
        bool succ = [db executeUpdate:sql];
        DebugNSLog(@"create table %@ result =%d ", TABLE_NM_HISDATA_ALL_DEBUG, succ);
    
    }];
//#endif
    
}




+(void)mutiInsertAlldata:(NSString * _Nonnull)macAdres
                   Array:(NSArray <SRHistoryDataSR03 *> *)dataArray
                Cpmplete:(void(^)(NSMutableArray<SRHistoryDataSR03 *> *dataArray, BOOL isSucc))cmpBlk {
//#if SAVE_ALL_HIS_FOR_DEBUG == 1

    if (!dataArray.count) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cmpBlk(nil, NO);
        });
    }
    
    WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        STRONG_SELF
        
        // 准备存储
        [db beginTransaction];
        BOOL allSucc = YES;
        NSMutableArray<SRHistoryDataSR03 *> *resArray = [NSMutableArray new];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        for (int i = 0; i < dataArray.count; i++) {
            
            SRHistoryDataSR03 *dataObj = dataArray[i];
           
        
            [resArray addObject:dataObj];
                
            NSString *sqlString = [NSString stringWithFormat:  @"INSERT OR IGNORE INTO %@ (time , macAdres, dataUuid, isWear, soprtTimes, steps, skinTemp, bloodOxygen, hrv, deviceModifyHeartRate, heart_ori_1, heart_ori_2, heart_ori_3, measureType, br, isSportMode, lis2ds12, isCharging, fmtTime, battery) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", TABLE_NM_HISDATA_ALL_DEBUG];
            if (!dataObj.hrv) {
                dataObj.hrv = [dataObj calcHRv];
            }
            
//            if (!dataObj.breathRate) {
//                dataObj.breathRate = [dataObj calcBr]; // 兼容14531-01 前 旧设备
//            }
            
            NSNumber *steps = dataObj.steps;
            
            
            BOOL succ = [db executeUpdate:sqlString,
                         dataObj.timeStamp,
                         macAdres,
                         dataObj.dataUuid,
                         dataObj.isWear,
                         dataObj.soprtTimes,
                         steps,
                         dataObj.skinTemp,
                         dataObj.bloodOxygen,
                         dataObj.hrv, /* hrv */
                         dataObj.deviceModifyHeartRate,
                         dataObj.heart_ori_1,
                         dataObj.heart_ori_2,
                         dataObj.heart_ori_3,
                         @(dataObj.measureType),
                         dataObj.breathRate, // V1.2.0 新增呼吸率, 呼吸率由设备上报
                         @(dataObj.isSportMode.boolValue),
                         @(dataObj.lis2ds12),
                         @(dataObj.isCharging),
                         [fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:dataObj.timeStamp.doubleValue]],
                         dataObj.battery
                         
                        ];
            
            allSucc = allSucc && succ;
        }
        
        
        [db commit];
        
        if (cmpBlk) {
            dispatch_async(dispatch_get_main_queue(), ^{
                cmpBlk(resArray, allSucc);
            });
        }
        
    }];
//#endif
}

+(void)deleteFromTime:(NSTimeInterval)time Account:(NSString *)macAdres Cpmplete:(void(^)( BOOL isSucc))cmpBlk
{
    
    // 1660891693 - 12 * 3600
    WEAK_SELF
    [[HMDBManager instance].dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        STRONG_SELF
        [db beginTransaction];
        
        NSString *sql =  [NSString stringWithFormat:@"DELETE FROM %@ WHERE time >  ? AND macAdres = ?", TABLE_NM_HISDATA_ALL_DEBUG];
        BOOL succ = [db executeUpdate:sql, @(time), macAdres];
        [db commit];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (cmpBlk) {
                cmpBlk(succ);
            }
        });
       
    }];
}




@end
